<template>
  <div class="clock-wrap">
    <div class="header">
      <router-link to="/">
         <a-icon type="left" class="icon"/>
      </router-link>
      <span class="clockTit">
        计时器
      </span>
    </div>
    <div class="countDown">
       <span>{{h_}}:</span>
       <span>{{m_}}:</span>
       <span>{{s_}}</span>
    </div>
    <div class="control">
      <img :src="startUrl[startIndex]" alt="请稍等" @click="startTimer">
      <img src="../../../static/images/index/reset.png" alt="请稍等" @click="resetTimer">
    </div>
  </div>
</template>

<script>
export default {
  name: 'Clock',
  data () {
    return {
      h: 0,
      m: 0,
      ms: 0,
      s: 0,
      h_: '00',
      m_: '00',
      ms_: '00',
      s_: '00',
      time: 0,
      myTime: '',
      startUrl: [require('../../../static/images/index/start.png'), require('../../../static/images/index/stop.png')],
      startIndex: 0
    }
  },
  methods: {
    timer () {
      // 定义计时器函数
      this.ms = this.ms + 50 // 毫秒
      if (this.ms >= 1000) {
        this.ms = 0
        this.s = this.s + 1
      }
      if (this.s >= 60) {
        this.s = 0
        this.m = this.m + 1
      }
      if (this.m >= 60) {
        this.m = 0
        this.h = this.h + 1
      }
      this.h_ = this.toDub(this.h)
      this.m_ = this.toDub(this.m)
      this.s_ = this.toDub(this.s)
    },
    toDub (n) {
      if (n < 10) {
        return '0' + n
      } else {
        return '' + n
      }
    },
    startTimer () {
      if (this.startIndex === 0) {
        this.startIndex = 1
        this.time = setInterval(this.timer, 50)
      } else {
        this.startIndex = 0
        clearInterval(this.time)
      }
    },
    resetTimer () {
      clearInterval(this.time)
      this.h_ = '00'
      this.m_ = '00'
      this.s_ = '00'
      this.h = 0
      this.m = 0
      this.s = 0
      if (this.startIndex === 1) {
        this.startIndex = 0
      }
    }
  },
  beforeDestroy () {
    clearInterval(this.time)
  }
}
</script>

<style lang="stylus" scoped>
@import '../../../static/css/color.styl'
  .header{
    text-align: left
    height: .98rem
    line-height: .98rem
    background-color: $color-main
    .icon{
      color: #fff
      padding: 0 .4rem
    }
    .clockTit{
      color: #fff
      position: absolute
      font-size: .4rem
    }
  }
  .clock-wrap{
    width: 100%
    height: 100%
    background: linear-gradient(45deg, #62c3d3, #1389bc)
    .countDown{
      text-align: center
      padding: 4rem 0 1rem 0
      font-size: 1.2rem
      color: #fff
    }
    .control{
      text-align: center
      img{
        width: 1.2rem
        margin: 0 1rem
      }
    }
  }
</style>
